<template>
  <div
    class="page-mobile-study-situation"
  >
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="title"
    ></white-header>
    <div class="hospital" v-if="action == 'hospital'">
      <van-search
        class="search"
        v-model="keyword"
        shape="round"
        background="#f7f8fa"
        placeholder="搜索医院"
        @input="searchHandle"
      />
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-if="type == 'region'" v-for="item in regionList" :key="item.id" :title="item.name" @click="regionHandle(item)"/>
        <van-cell v-if="type == 'hospital'" v-for="item in hospitalList" :key="item.id" :title="item.name" @click="hospitalHandle(item)"/>
      </van-list>
    </div>
    <div class="department" v-if="action == 'department'">
      <van-tree-select
        :items="departmentData"
        height="calc(100vh - .9rem)"
        :active-id.sync="classifyActiveId"
        :main-active-index.sync="classifyActiveIndex"
        @click-item="departmentHandle"
      />
    </div>
  </div>
</template>

<script>
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { getProfessionalList, getIdentityList,getHospitalList,getDepartmentList,getDepartmentTree,getDistrictIndex } from "~/api/authentication";
const defaultRegionAttr={
  province:{},
  city:{},
  district:{},
}//记录地区
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      action:"",//页面类型
      keyword:"",//搜索关键词
      regionList: [],//地区/医院数组
      loading: false,//加载更多动画
      finished: false,//是否加载完全部数据
      classifyActiveId: 1,//分类右侧高亮选项的 id
      classifyActiveIndex: 0,//分类左侧高亮选项的索引
      departmentList:[],//科室列表
      regionType:1,//1省2市3区
      regionAttr:Object.assign({},defaultRegionAttr),//记录地区
      hospitalList:[],//医院列表
      type:"region",//region地区/hospital医院
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      user_info(state) {
        return state.user_info;
      },
      class_list(state) {
        return state.class_list;
      },
      is_loading(state) {
        return state.is_loading;
      },
      authentication(state) {
        return state.authentication;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      }
    }),
    departmentData(){
      //第一种方法->已失效
      // let departmentParent = [];
      // this.departmentList.forEach(item=>{
      //   let departmentChild = [];
      //   item.departmentList.forEach(item=>{
      //     departmentChild.push({id:item.id,text:item.name})
      //   })
      //   departmentParent.push({text:item.name,children:departmentChild})
      // })
      // return departmentParent;
      //第二种方法->已失效
      if(this.departmentList.length > 0){
        // return this.departmentList.map(item=>{
        //   return {text:item.name,children:item.departmentList.map(item=>{
        //     return {id:item.id,text:item.name};
        //   })}
        // })
        //拿到一级科室
        let oneDepartment = this.departmentList.filter(item=>!item.parentId).map(item=>{return {id:item.id,text:item.name}});
        for (let index = 0; index < oneDepartment.length; index++) {
            //拿到二级科室
            let twoDepartment = this.departmentList.filter(item=>item.parentId == oneDepartment[index].id).map(item=>{return {id:item.id,text:item.name}});
            //把二级科室挂载到一级科室
            oneDepartment[index] = {...oneDepartment[index],children:twoDepartment}
        }
        return oneDepartment;
      }else{
        return [];
      }
      
    }
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING","SET_AUTHENTICATION","UPDATE_AUTHENTICATION"]),
    //跳转路径
    toPath(path) {
      this.$router.push(path);
    },
    //点击地区处理函数
    regionHandle(data){
      if(this.regionType == 1){
        console.log("省id",data.id);
        this.regionType = 2;
        this.regionAttr.province = data;
        this.getRegionList({parentId:data.id})
      }else if(this.regionType == 2){
        console.log("市id",data.id);
        this.regionAttr.city = data;
        if(this.regionAttr.province.directly == 1){
          this.getHospital({cityId:data.id});
        }else{
          this.regionType = 3;
          this.getRegionList({parentId:data.id})
        }
      }else if(this.regionType == 3){
        console.log("区id",data.id);
        this.regionAttr.district = data;
        this.getHospital({areaId:data.id});
      }
    },
    //点击医院处理函数
    hospitalHandle(data){
      console.log("选择医院",data);
      this.UPDATE_AUTHENTICATION({hospitalId:data.id})
      this.$router.back();
    },
    //列表懒加载
    onLoad() {
        // 异步更新数据
        // setTimeout 仅做示例，真实场景中一般为 ajax 请求
        // setTimeout(() => {
        //   for (let i = 0; i < 20; i++) {
        //     this.regionList.push(this.regionList.length + 1);
        //   }

        //   // 加载状态结束
        //   this.loading = false;

        //   // 数据全部加载完成
        //   if (this.regionList.length >= 40) {
        //     this.finished = true;
        //   }
        // }, 1000);
        this.finished = true;
    },
    //搜索医院处理函数
    async searchHandle(val){
      if(!val.trim()){
        this.type = 'region';
        return false;
      }
      console.log("搜索关键词",val);
      this.SET_IS_LOADING(true);
      this.type = 'hospital';
      let params = {
        keyword:val.trim()
      };
      let result = await getHospitalList(params);
      if (result && result.data && result.data.code == 200) {
        this.hospitalList = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //点击科室处理函数
    departmentHandle(data){
      console.log("选择的科室",data);
      this.UPDATE_AUTHENTICATION({departmentId:data.id})
      this.$router.back();
    },
    //获取科室列表
    async getDepartment() {
      this.SET_IS_LOADING(true);
      // console.log(this.$route.query);
      // const { departmentId } = this.$route.query
      // if(departmentId != "null"){
        // let result = await getDepartmentTree(departmentId);
        // if (result && result.data && result.data.code == 200) {
        //   this.departmentList = result.data.data;
        // } else {
        //   this.$toast("网络波动，请稍后再试！");
        // }
      // }else{
      //   this.departmentList = [];
      // }
      let result = await getDepartmentList();
        if (result && result.data && result.data.code == 200) {
          this.departmentList = result.data.data.rows;
        } else {
          this.$toast("网络波动，请稍后再试！");
        }
      this.SET_IS_LOADING(false);
    },
    //获取地区
    async getRegionList(data = {}) {
      this.SET_IS_LOADING(true);
      this.type = 'region';
      let params = {
        type:this.regionType,
        ...data
      };
      let result = await getDistrictIndex(params);
      if (result && result.data && result.data.code == 200) {
        this.regionList = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //获取医院
    async getHospital(data = {}) {
      this.SET_IS_LOADING(true);
      this.type = 'hospital';
      let params = {
        ...data
      };
      let result = await getHospitalList(params);
      if (result && result.data && result.data.code == 200) {
        this.hospitalList = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    async getData() {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        
        this.SET_IS_LOADING(false);
      })
        .then()
        .catch(e => {
          this.SET_IS_LOADING(false);
        });
    },
    //初始化页面
    initPage() {
      return new Promise((res, rej) => {
        if (process.client) {
          try {
            this.action = this.$route.query.action;
            if (this.action == "hospital") {
              this.title = "选择医院";
              this.regionType = 1;
              this.regionAttr = Object.assign({},defaultRegionAttr);
              this.type = 'region';
              this.getRegionList()
            } else if (this.action == "department") {
              this.title = "选择科室";
              this.getDepartment();
            }
            this.getData();
            res("success");
          } catch (e) {
            console.log(e);
            rej(e);
          }
        }
      }).then();
    },
    
  },
  activated() {
    if (process.client) {
      this.initPage();
      this.keyword = "";
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
  },
  deactivated() {
    this.setDisabled(true);
  },
  beforeDestroy() {
  },
  created() {
    //开启下拉刷新
    this.setDisabled(false);
    //初始化页面数据
    this.initPage();
    //下拉回调
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
    //返回上次页面滚动条的位置
    // this.$nextTick(() => {
    //   document.body.scrollTop = this.scroll_heigth;
    //   document.documentElement.scrollTop = this.scroll_heigth;
    // });
  },
  mounted() {
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-study-situation {
  //   min-height: calc(100vh - 1.6rem);
  min-height: 100vh;
  // .hospital{
  // }
  // .department{}
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
}
.page-mobile-study-situation.complete_test {
  background: #f7f7fa;
}
</style>
<style lang="scss">
.page-mobile-study-situation {
  .van-popup {
    width: 7.2rem;
  }
  .van-search__content{
    background-color: #ffffff;
  }
  .van-tree-select__item--active {
      color: var(--theme-color);
  }
}
</style>
